<script setup>
import {ref, onMounted, computed, nextTick} from 'vue'
import {ElTable, ElTableColumn, ElMessage, ElTag} from "element-plus";
import Drawer from "@/components/Drawer.vue";
import AssetsList from '@/components/AssetsList.vue'
import {
  getTransferList,
  getTransferById,
  deptList,
  getLocationTree,
  addTransfer
} from "@/api/AssetTransfer"

// 引入图标
import {Search, Refresh, Plus, View} from '@element-plus/icons-vue'

/***********资产调拨表单数据******** */
// 新增资产调拨弹框状态
const formVisible = ref(false)
// 资产调拨弹框标题
const title = ref('')
// 资产列表搜索框绑定的调拨单号
const queryForm = ref({orderNo: ''})
// 控制 Drawer 显示状态
const drawerVisible = ref(false)
// 资源调拨列表数据
const transferList = ref([])
// 资产借用表单数据
const TransferForm = ref({
  toDeptId: null,
  toLocationId: null,
  reason: null,
  trackingNumber: null,
  remark: "",
  transferDetails: []
})
// 可调拨资产列表数据
const assetList = ref([])
// 定义 Drawer 数据展示表单
const showFormData = ref({
  id: '',
  status: "",
  orderNo: '',
  createTime: '',
  operator: '',
  toCompanyName: '',
  toDeptName: '',
  toLocationName: '',
  remark: '',
  transferDetails: []
})

// 在 script setup 部分添加
const transferStatus = computed(() => {
  switch (showFormData.value.status) {
    case "0":
      return '待调拨';
    case "1":
      return '部分调拨';
    case "2":
      return '已完成';
    case "3":
      return '已取消';
    default:
      return '未知状态';
  }
});

//定义 Drawer 数据展示表单值
const formDataValues = computed(() => [
  {
    label: '调入部门:',
    value: showFormData.value.toDeptName
  },
  {
    label: '调入公司:',
    value: showFormData.value.toCompanyName
  },
  {
    label: '创建人:',
    value: showFormData.value.operator
  },
  {
    label: '调入位置:',
    value: showFormData.value.toLocationName
  },
  {
    label: '调拨状态:',
    value: transferStatus.value
  },
  {
    label: '调拨单号:',
    value: showFormData.value.orderNo
  },
  {
    label: '创建时间:',
    value: showFormData.value.createTime
  },

  {
    label: '备注:',
    value: showFormData.value.remark
  }
])
// 定义 Drawer table数据展示列
const tableColumns = ref([
  // {prop: 'assetId', label: '资产ID'},
  {prop: 'assetCode', label: '资产编码'},
  {prop: 'name', label: '资产名称'},
  {prop: 'categoryName', label: '资产分类'},
  {prop: 'model', label: '型号规格'},
  // {prop: 'serialNumber', label: '设备序列号'},
  // { prop: 'pic', label: '图片' },
  //{prop: 'status', label: '状态'},
  {prop: 'locationName', label: '所在位置'},
  {prop: 'companyName', label: '所在公司'},
  {prop: 'deptName', label: '所在部门'},
  // {prop: 'reason', label: '调拨原因'},
  // {prop: 'trackingNumber', label: '快递单号'}
])
// 定义 Drawer table数据展示列值
const tableData = ref([])
//drawer组件的标题
const drawerTitle = ref('调拨详细')
// 资产所在部门列表数据
const assetDept = ref([]);
// 借用后资产位置树形数据
const parentLocations = ref([])
// 定义子组件 ref
const assetsListRef = ref(null)
// 是否为编辑状态
const isEditMode = ref(false)
// 资产调拨表单实例对象
const formRef = ref(null)

//点击调拨按钮
const addTransferData = () => {
  //弹框显示
  formVisible.value = true
  //弹框标题
  title.value = '新增资产调拨'
}

// 根据调拨单号查询调拨列表
const handleTransferSearch = () => {
  if (!queryForm.value.orderNo) {
    ElMessage.warning('请输入调拨单号');
    return;
  }
  const params = {
    orderNo: queryForm.value.orderNo
  }
  getTransferList(params).then(res => {
    if (res.code === 200) {
      transferList.value = res.data
    }
  })
}

// 重置资源调拨列表数据
const handleTransferReset = () => {
  queryForm.value.orderNo = ''
  getTransferAssetListData()
}

// 获取调拨列表
const getTransferAssetListData = () => {
  getTransferList().then(res => {
    if (res.code === 200) {
      transferList.value = res.data
    }
  })
}

// 点击编号时触发打开Drawer的方法
const handleClickTag = (id) => {
  // 给Drawer传递数据 打开 Drawer 并情况之前数据
  showFormData.value = {
    id: '',
    status: "",
    orderNo: '',
    createTime: '',
    operator: '',
    toCompanyName: '',
    toDeptName: '',
    toLocationName: '',
    remark: '',
    transferDetails: []
  }
  tableData.value = []
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getTransferById(id).then(res => {
    if (res.code === 200) {
      console.log(res, "详情数据")
      nextTick(() => {
        showFormData.value.id = res.data.id
        showFormData.value.orderNo = res.data.orderNo
        showFormData.value.toDeptName = res.data.toDeptName
        showFormData.value.toCompanyName = res.data.toCompanyName
        showFormData.value.toLocationName = res.data.toLocationName
        showFormData.value.status = res.data.status
        showFormData.value.operator = res.data.operator
        showFormData.value.createTime = res.data.createTime
        showFormData.value.remark = res.data.remark
        tableData.value = res.data.transferDetails
        console.log(formDataValues.value, 7777)
      })
    }
  })
  // 获取到数据后 给showFormData 赋值
  drawerVisible.value = true
}

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false
}

const rules = {
  toDeptId: [
    {required: true, message: '请选择调入部门', trigger: 'change'}
  ],
  toLocationId: [
    {required: true, message: '请选择调入位置', trigger: 'change'}
  ],
  reason: [
    {required: true, message: '请输入调拨有原因', trigger: 'blur'},
  ],
  remark: [
    {max: 200, message: '备注长度不能超过200个字符', trigger: 'blur'}
  ]
}

// 点击取消关闭弹框
const handleCancel = () => {
  formVisible.value = false
  // 调用子组件的取消选中方法
  assetsListRef.value?.clearSelection()
}

// 获取子组件选择借用的资产
const handleAssetSelect = (assetList) => {
  TransferForm.value.transferDetails = assetList
}

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then(res => {
    if (res.code === 200) {
      parentLocations.value = res.data
    }
  })
}

// 获取部门树形结构
const getDeptList = () => {
  deptList().then(res => {
    if (res.code === 200) {
      assetDept.value = res.data
    }
  })
}

// 提交资产调用表单
const handleSubmit = () => {
  // 添加表单校验
  console.log(TransferForm.value, 789)
  if (TransferForm.value.transferDetails.length <= 0) return ElMessage.error('请选择资产')
  formRef.value.validate(async (valid) => {
    if (valid) {
      addTransfer(TransferForm.value).then(res => {
        if (res.code === 200) {
          ElMessage.success(`新增成功`);
          formVisible.value = false;
          // 调用子组件的取消选中方法
          assetsListRef.value?.clearSelection()
          resetForm();
          getTransferAssetListData()
        }
      });
    }
  })
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  formRef.value?.resetFields();
  TransferForm.value = {
    toDeptId: null,
    toLocationId: null,
    reason: null,
    trackingNumber: null,
    remark: "",
    transferDetails: []
  }
}

/*********** 页面加载时获取数据 *********/
onMounted(() => {
  //获取位置树数据
  getLocationTreeData()
  //获取部门树数据
  getDeptList()
  //获取调拨列表数据
  getTransferAssetListData()
})

</script>

<template>

  <!-- 新增搜索框 -->
  <el-form :inline="true" :model="queryForm" style="margin: 10px 0 0 0;">
  <el-form-item>
        <el-space>
          <el-input v-model="queryForm.orderNo" placeholder="调拨单号" clearable style="width: 300px"
                    :prefix-icon="Search">
            <template #append>
              <el-button type="primary" style="background: #409eff;color: #ffffff;" :icon="Search"
                         @click="handleTransferSearch">
                搜索
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" plain :icon="Refresh" @click="handleTransferReset">重置</el-button>
          <el-button plain type="primary" :icon="Plus" @click="addTransferData">新增
          </el-button>
        </el-space>
      </el-form-item>
  </el-form>


  <el-dialog v-model="formVisible" @close="handleCancel" close-on-click-modal="false" :title="title" width="70%">
    <el-form :model="TransferForm" :rules="rules" ref="formRef" label-width="120px" inline>
      <el-form-item label="调入部门" prop="toDeptId" :rules="[{required:true,message:'请选择调入部门'}]">
        <el-tree-select
            v-model="TransferForm.toDeptId" placeholder="请选择调入部门"
            :data="assetDept"
            node-key="id"
            clearable
            :props="{label:'deptName',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>
      </el-form-item>

      <el-form-item label="调入位置" prop="toLocationId" :rules="[{required:true,message:'请选择调入位置'}]">
        <el-tree-select
            v-model="TransferForm.toLocationId" placeholder="请选择调入位置"
            :data="parentLocations"
            node-key="id"
            clearable
            :props="{label:'locationName',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 200px"
        ></el-tree-select>

      </el-form-item>

      <el-form-item label="调拨原因" prop="reason" :rules="[{required:true,message:'请选择调拨原因'}]">
        <el-input v-model="TransferForm.reason" clearable placeholder="请输入调拨原因" show-word-limit
                  style="width: 200px"/>
      </el-form-item>

      <el-form-item label="快递单号" prop="trackingNumber">
        <el-input v-model="TransferForm.trackingNumber" clearable placeholder="请输入快递单号" show-word-limit
                  style="width: 200px"/>
      </el-form-item>

      <el-form-item label="备注" class="full-width">
        <el-input
            v-model="TransferForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注内容"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>

      <!-- 资产列表 -->
      <AssetsList :status="0" ref="assetsListRef" @assetSelect="handleAssetSelect"/>

      <div class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>
  <el-table :data="transferList"
            table-layout="auto"
            height="80%"
            style="margin-top: 10px;"
  >
    <el-table-column prop="orderNo" label="调拨单号" align="left" width="160"/>
    <el-table-column prop="toCompanyName" label="调入公司" align="center"/>
    <el-table-column prop="toDeptName" label="调入部门" align="center"/>
    <el-table-column prop="operator" label="创建人" align="center"/>
    <el-table-column prop="status" label="单据状态" align="center">
      <template #default="scope">
        <el-tag type="primary" v-if="scope.row.status==0">待调拨</el-tag>
        <el-tag type="warning" v-if="scope.row.status==1">部分调拨</el-tag>
        <el-tag type="success" v-if="scope.row.status==2">已完成</el-tag>
        <el-tag type="info" v-if="scope.row.status==3">已取消</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="toLocationName" label="调入位置" align="center"/>
    <!--    <el-table-column prop="remark" label="备注" align="center">-->
    <!--      <template #default="scope">-->
    <!--        <el-tooltip :content="scope.row.remark" placement="top"-->
    <!--                    :disabled="!scope.row.remark || scope.row.remark.length <= 10">-->
    <!--          <span class="table-cell-truncate">{{ scope.row.remark }}</span>-->
    <!--        </el-tooltip>-->
    <!--      </template>-->
    <!--    </el-table-column>-->
    <el-table-column prop="createTime" label="创建时间" align="center"/>
    <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-link type="primary" :icon="View" @click="handleClickTag(scope.row.id)">查看</el-link>
          </template>
    </el-table-column>
  </el-table>

  <!-- 新增 Drawer 组件 -->
  <Drawer v-model:visible="drawerVisible" :title=drawerTitle :formData="showFormData" :formDataValues="formDataValues"
          :tableColumns="tableColumns" :tableData="tableData" @close="closeDrawer"/>

</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409EFF;

    &::after {
      content: '（可选）';
      font-size: 12px;
      color: #999;
    }
  }
}

.full-width {
  width: 100%;

  .el-textarea {
    width: 100%;
  }
}

.table-cell-truncate {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际情况调整 */
}
</style>